package com.py.framework.core.controller;

import org.apache.commons.lang.StringUtils;

import com.py.framework.core.common.Page;
import com.py.framework.core.rest.support.RestServiceResult;

/**
 * 基础控制器
 * @author Leegern
 * @date   2018年4月20日
 */
public abstract class BaseController {
	
	private static final int NUMBER_ZERO = 0;
	
	
	/**
	 * 获取当前分页实体
	 * @param currentPage 当前页码
	 * @param pageSize    分页大小
	 * @return
	 */
	protected Page getPage(int currentPage, int pageSize) {
		Page page = new Page();
		if (currentPage > NUMBER_ZERO) {
			page.setCurrentPage(currentPage);
		}
		if (pageSize > NUMBER_ZERO) {
			page.setPageSize(pageSize);
		}
		return page;
	}
	
	/**
	 * 获取成功的返回对象
	 * @return
	 */
	protected <T> RestServiceResult<T> getSuccessRestServiceResult() {
		return this.getRestServiceResult(RestServiceResult.CODE_SUCCESS, StringUtils.EMPTY, NUMBER_ZERO, null);
	}
	
	/**
	 * 获取成功的返回对象
	 * @param data  数据结果集
	 * @return
	 */
	protected <T> RestServiceResult<T> getSuccessRestServiceResult(T data) {
		return this.getRestServiceResult(RestServiceResult.CODE_SUCCESS, StringUtils.EMPTY, NUMBER_ZERO, data);
	}
	
	/**
	 * 获取成功的返回对象(分页查询)
	 * @param count 总条数
	 * @param data  数据结果集
	 * @return
	 */
	protected <T> RestServiceResult<T> getPageSuccessRestServiceResult(int count, T data) {
		return this.getRestServiceResult(RestServiceResult.CODE_SUCCESS, StringUtils.EMPTY, count, data);
	}
	
	/**
	 * 获取失败的返回对象
	 * @param errorMsg 错误信息
	 * @return
	 */
	protected <T> RestServiceResult<T> getFailedRestServiceResult(String errorMsg) {
		return this.getRestServiceResult(RestServiceResult.CODE_UNKNOW, errorMsg, NUMBER_ZERO, null);
	}
	
	/**
	 *  获取返回对象
	 * @param code   状态码
	 * @param msg    消息
	 * @param count  总记录数
	 * @param data   数据结果集
	 * @return
	 */
	protected <T> RestServiceResult<T> getRestServiceResult(int code, String msg, int count, T data) {
		RestServiceResult<T> result = new RestServiceResult<>();
		result.setCode(code);
		if (StringUtils.isBlank(msg) && RestServiceResult.CODE_SUCCESS != code) {
			result.setMsg("操作失败！");
		} else {
			result.setMsg(msg);
		}
		result.setData(data);
		result.setCount(count);
		return result;
	}
}